package com.example.jn_dxs.Ui;


import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.loadable.LoadStatusChangedEvent;
import com.esri.arcgisruntime.loadable.LoadStatusChangedListener;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.example.jn_dxs.Base.BaseActivity;
import com.example.jn_dxs.Base.BaseViewModel;
import com.example.jn_dxs.R;
import com.example.jn_dxs.Ui.activity.StatisticsActivity;
import com.example.jn_dxs.Utlis.TMapLayer;
import com.example.jn_dxs.databinding.ActivityMapBinding;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import me.jessyan.autosize.internal.CancelAdapt;

public class MapActivity extends BaseActivity<BaseViewModel, ActivityMapBinding> implements CancelAdapt {

    private ServiceFeatureTable mServiceFeatureTable;
    private FeatureLayer featureLayer;
    private Callout mCallout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    public void initClick() {
        binding.Portrait.setOnClickListener(v -> {
            binding.Vector.setSelected(true);
            binding.Portrait.setSelected(false);
            selectItem(1);
        });
        binding.Vector.setOnClickListener(v -> {
            binding.Vector.setSelected(false);
            binding.Portrait.setSelected(true);
            selectItem(0);
        });
        binding.mine.setOnClickListener(v -> {

        });
    }

    @Override
    protected void initEventAndView() {

        binding.MapView.setAttributionTextVisible(false);
        mCallout = binding.MapView.getCallout();
        TMapLayer t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_VECTOR_2000);
        String url = "http://60.216.249.11:6080/arcgis/rest/services/LW/LWDHPT/MapServer/2";
        mServiceFeatureTable = new ServiceFeatureTable(url);
        mServiceFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        mServiceFeatureTable.addLoadStatusChangedListener(new LoadStatusChangedListener() {
            @Override
            public void loadStatusChanged(LoadStatusChangedEvent loadStatusChangedEvent) {
                String a = loadStatusChangedEvent.getNewLoadStatus().toString();
                if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.LOADED) {

                }
            }
        });

        featureLayer = new FeatureLayer(mServiceFeatureTable);
        featureLayer.setScaleSymbols(true);
        featureLayer.setLabelsEnabled(true);
        featureLayer.setPopupEnabled(true);
        // set tiled layer as basemap
        Basemap basemap = new Basemap(t_vec);
        // create a map with the basemap
        ArcGISMap map = new ArcGISMap(basemap);
        // create a viewpoint from lat, long, scale  湖北 14.294401,30.596871   济南 117.046055,36.653832    莱芜 117.662538,36.290729
        Viewpoint viewpoint = new Viewpoint(36.290729, 117.662538, 100000);
        // set initial map extent
        map.setInitialViewpoint(viewpoint);
        map.getOperationalLayers().add(featureLayer);
        // set the map to be displayed in this view

        binding.MapView.setMap(map);
        binding.MapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, binding.MapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                // remove any existing callouts
                if (mCallout.isShowing()) {
                    mCallout.dismiss();
                }
                final com.esri.arcgisruntime.geometry.Point clickPoint = mMapView
                        .screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                // create a selection tolerance
                int tolerance = 10;
                double mapTolerance = tolerance * mMapView.getUnitsPerDensityIndependentPixel();
                // use tolerance to create an envelope to query
                Envelope envelope = new Envelope(clickPoint.getX() - mapTolerance, clickPoint.getY() - mapTolerance,
                        clickPoint.getX() + mapTolerance, clickPoint.getY() + mapTolerance, map.getSpatialReference());
                QueryParameters query = new QueryParameters();
                query.setGeometry(envelope);
                final ListenableFuture<FeatureQueryResult> future = mServiceFeatureTable
                        .queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
                // add done loading listener to fire when the selection returns
                future.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //call get on the future to get the result
                            FeatureQueryResult result = future.get();
                            // create an Iterator
                            Iterator<Feature> iterator = result.iterator();
                            View CallView = View.inflate(MapActivity.this, R.layout.popu_map, null);
                            TextView id = CallView.findViewById(R.id.Id);
                            TextView Location = CallView.findViewById(R.id.Location);
                            TextView Type = CallView.findViewById(R.id.Type);
                            TextView Msg = CallView.findViewById(R.id.Msg);
                            TextView Status = CallView.findViewById(R.id.Status);
                            TextView Detail = CallView.findViewById(R.id.Detail);
                            Detail.setOnClickListener(v -> {
                                startActivity(new Intent(MapActivity.this, StatisticsActivity.class));
                            });
                            // cycle through selections
                            Feature feature;
                            while (iterator.hasNext()) {
                                feature = iterator.next();
                                // create a Map of all available attributes as name value pairs
                                Map<String, Object> attr = feature.getAttributes();
                                Set<String> keys = attr.keySet();
                                for (String key : keys) {
                                    Object value = attr.get(key);
                                    // format observed field value as date
//                                    if (value instanceof GregorianCalendar) {
//                                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
//                                        value = simpleDateFormat.format(((GregorianCalendar) value).getTime());
//                                    }
                                    // append name value pairs to TextView
                                    if (key.equals("pkiaa")){
                                        id.setText("统一编号：" + value);
                                    }
                                    if (key.equals("tkalb")){
                                        Location.setText("位置：" + value);
                                    }
                                    if (key.equals("swae")){
                                        Type.setText("监测点类型：" + value);
                                    }
                                    if (key.equals("sweb")){
                                        Msg.setText("监测内容：" + value);
                                    }
                                    if (key.equals("swefba")){
                                        Status.setText("监测井（点）状况：" + value);
                                    }
//                                    id.append(key + " | " + value + "\n");
                                }
                                // center the mapview on selected feature
                                Envelope envelope = feature.getGeometry().getExtent();
                                mMapView.setViewpointGeometryAsync(envelope, 200);
                                // show CallOut
                                mCallout.setLocation(clickPoint);
                                mCallout.setContent(CallView);
                                mCallout.show();
                            }
                        } catch (Exception e) {
                            Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e.getMessage());
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
        binding.Vector.setSelected(false);
        binding.Portrait.setSelected(true);




    }

    private void selectItem(int position) {


        TMapLayer t_vec;
        switch (position) {
            case 0:
                t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_VECTOR_2000);
                break;
            case 1:
                t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_IMAGE_2000);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + position);
        }

        // change the basemap to the new layer
        binding.MapView.getMap().setBasemap(new Basemap(t_vec));
    }

    @Override
    public void onPause() {
        if (binding.MapView != null) {
            binding.MapView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (binding.MapView != null) {
            binding.MapView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (binding.MapView != null) {
            binding.MapView.dispose();
        }
        super.onDestroy();
    }

}
